# 导入
import pygame,time
from plane_sprites import*
pygame.init()
timer_enemy1 = 1000 # 敌机1生成定时器
timer_enemy2 = 1500 # 敌机2生成定时器
timer_fire = 500    # 我机子弹生成定时器
life = 3            # 我机生命
score = 0           # 分数

class planeGame(object):
    # 主游戏
    def __init__(self):
        print('Game')
        # 1.绘制窗口
        self.screen = pygame.display.set_mode(SCREEN.size)
        
        # 字体
        self.font = pygame.font.SysFont('方正粗黑宋简体', 48, False, False)
        self.font_over = pygame.font.SysFont('方正粗黑宋简体', 75, False, False)
        self.text_score = self.font.render('score:' + str(score), True, (0, 0, 255))
        self.text_life = self.font.render('life:' + str(life), True, (0, 0, 255))
        self.text_over = self.font_over.render('game over', True, (0, 0, 255))
        # 2.创建游戏时钟
        self.clock = pygame.time.Clock()
        # 3.调用私有方法，精灵和精灵组的创建
        self.__create_sprites()
        # 4.设置定时器事件-创建敌机 1s=1000ms
        pygame.time.set_timer(CREATE_ENEMY_EVENT, timer_enemy1)
        pygame.time.set_timer(CREATE_ENEMY_EVENT2, timer_enemy2)
        # 5.设置定时器事件-发射子弹 0.5s=500ms
        pygame.time.set_timer(HERO_FIRE_EVENT, timer_fire)

        # 动画资源
        # 1.图片
        self.imglist_emeny = [pygame.image.load('images/enemy_down' + str(i) + '.png') for i in range(1, 3)]
        self.imglist_emeny2 = [pygame.image.load('images/enemy2_down' + str(i) + '.png') for i in range(1, 3)]
        self.imglist_hero = [pygame.image.load('images/hero_down' + str(i) + '.png') for i in range(1, 3)]
        # 2.坐标
        self.emx = 0
        self.emy = 0
        self.emx2 = 0
        self.emy2 = 0
        # 3.bool
        self.f1 = False
        self.f2 = False
        # 4.状态。1：正常，结束：0
        self.status = 1

    # 私有方法由__开头
    def __create_sprites(self):
        # 背景精灵
        bg1 = background()
        bg2 = background(True)
        # 背景精灵组
        self.back_group = pygame.sprite.Group(bg1,bg2)
        
        # 敌机精灵组
        self.enemy_group = pygame.sprite.Group()
        self.enemy_group2 = pygame.sprite.Group()
        # 英雄精灵和精灵组
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)

        # 播放音乐
        self.sound = gamesound()
        self.sound.playmusic()

    # 游戏函数
    def StartGame(self):
        print('Game is start')
        while True:
            # 1.设置帧率
            # self.clock.tick(60)
            self.clock.tick(FRAME_PER_SEC)

            # 2.事件监听
            self.__event_handler()
            # 3.碰撞检测
            self.__check_collide()
            # 4.更新/设置精灵组
            self.__update_sprites()
            # 5.更新game over
            self.__show_gameover()
            # 6.更新显示
            pygame.display.update()

    def __event_handler(self):
        for event in pygame.event.get():
            # 退出
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()

            # 定时器生产敌机
            if event.type == CREATE_ENEMY_EVENT:
                self.enemy = Enemy(ey_img)
                self.enemy_group.add(self.enemy)
            # 定时器生产敌机
            if event.type == CREATE_ENEMY_EVENT2:
                self.enemy2 = Enemy(ey2_img)
                self.enemy_group.add(self.enemy2)
            # 定时器生产子弹
            elif event.type == HERO_FIRE_EVENT:
                self.hero.fire()
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    # 按下右键
                    self.hero.speed = 2
                elif event.key == pygame.K_LEFT:
                    # 按下左键
                    self.hero.speed = -2
            # else:
            #     # 没按
            #     self.hero.speed = 0
            
            # 抬起
            if event.type == pygame.KEYUP:
                # 停下
                self.hero.speed = 0

    def __check_collide(self):
        global score
        global life
        # 子弹弹打中敌机
        # 4参数（碰撞检测对象1，碰撞检测对象2，
        # 对象1是否销毁，对象2是否销毁）
        sprite_dict = pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
        if sprite_dict:
            score += 1
                            # rander-显示文字
            self.text_score = self.font.render('score:' + str(score), True, (255, 255, 255))
            
            self.emx = list(sprite_dict.items())[0][1][0].rect.x
            self.emy = list(sprite_dict.items())[0][1][0].rect.y
            self.f1 = True

            self.sound.playbommusic()
        # 英雄撞上敌机
        enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
        if len(enemies) > 0:
            ey = enemies[0]
            hr = self.hero
            for i in range(2):
                self.back_group.draw(self.screen)
                self.screen.blit(self.imglist_emeny[i], (ey.rect.x, ey.rect.y))
                self.screen.blit(self.imglist_hero[i], (hr.rect.x, hr.rect.y))
                pygame.display.update()
            # 播放音乐0.3秒
            gamesound().playovermusic()
            time.sleep(0.3)
            # 结束界面
            # 负责减
            if life != 0:
                life -= 1
                self.text_life = self.font.render('life:' + str(life), True, (255, 255, 255))
            # 负责判断
            if life == 0:
                self.empty_all()
                self.draw_end()
                self.game_over()
            # 结束游戏
            # planeGame.game_over()

    def __update_sprites(self):
        # 背景精灵更新位置
        self.back_group.update()
        # draw一下
        self.back_group.draw(self.screen)

        # 敌机精灵更新位置
        self.enemy_group.update()
        # draw一下
        self.enemy_group.draw(self.screen)

        # 敌机精灵更新位置
        self.enemy_group2.update()
        # draw一下
        self.enemy_group2.draw(self.screen)

        # 我机精灵更新位置
        self.hero_group.update()
        # draw一下
        self.hero_group.draw(self.screen)

        # 子弹精灵更新位置
        self.hero.bullets.update()
        # draw一下
        self.hero.bullets.draw(self.screen)

        self.screen.blit(self.text_score, (8, SCREEN.height - 80))
        self.screen.blit(self.text_life, (SCREEN.width - 110, SCREEN.height - 80))
        

        if self.f1:
            for i in range(2):
                self.screen.blit(self.imglist_emeny[i], (self.emx, self.emy))
            self.f1 = False

    def __show_gameover(self):
        if self.status == 0:
            self.screen.blit(self.text_over, (SCREEN.width/4 - 25, SCREEN.height/2))

    # 结束界面
    def empty_all(self):
        # 清空对象
        # 定时器清空
        pygame.time.set_timer(CREATE_ENEMY_EVENT, 0)
        pygame.time.set_timer(CREATE_ENEMY_EVENT2, 0)
        pygame.time.set_timer(HERO_FIRE_EVENT, 0)
        # 精灵清空
        self.hero.bullets.empty()
        self.hero.kill()
        self.hero_group.empty()

        self.enemy.kill()
        self.enemy_group.empty()
        self.enemy2.kill()
        self.enemy_group2.empty()

        pygame.event.clear()

        # 停止音乐
        pygame.mixer.music.stop()
        pygame.mixer.stop()

    def draw_end(self):
        # 重新绘制页面
        self.screen.fill((0, 0, 0))
        image = pygame.image.load(bg_img)
        self.screen.blit(image, (0, 0))

        pygame.display.update()

    def game_over(self):
        print("game over")
        self.status = 0


if __name__ == "__main__":
    # 创建游戏对象
    game = planeGame()
    # 开始游戏
    game.StartGame()
